package CommonGui;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.print.PageFormat;
import java.awt.print.Printable;

//Base painting Image objects class
public abstract class ImagePainter extends Component implements Printable
{
	private static final long serialVersionUID  =  1L;
	private static final long DOTS_PER_INCH     =  72L;
	protected Image image;
	
	
	public ImagePainter(Image image) {
		this.image = image;
	}
	
	
	// Returns draw coordinates
	protected Rectangle getDrawRect(PageFormat pageFormat)
	{	
		Dimension imageSize = getImageDpiSize();
		
		// Do resize if image size is more than page size
		if (imageSize.width > pageFormat.getImageableWidth() ||
			imageSize.height > pageFormat.getImageableHeight())
		{				
			double scale = getScaleByPageSize(pageFormat);
			
			double width = imageSize.width / scale;
			double heigth = imageSize.height / scale;			
			
			return new Rectangle(0, 0, (int)width, (int)heigth);
		}
		
		// Returns draw coordinates
		return new Rectangle(0, 0, imageSize.width, imageSize.height);
	}
	
	
	// Returning scale to print the whole image on a 1 page
	protected double getScaleByPageSize(PageFormat pageFormat)
	{
		double scale = 1;
		Dimension imageSize = getImageDpiSize();
		
		// If it's bigger we shall do nothing
		if (imageSize.width > pageFormat.getImageableWidth() ||
			imageSize.height > pageFormat.getImageableHeight())
		{				
			double widthScale = imageSize.width / pageFormat.getImageableWidth();
			double heigthScale = imageSize.height / pageFormat.getImageableHeight();
			
			scale = Math.max(widthScale, heigthScale); 
		}
		
		return scale;
	}
	
	
	// Calculates image size in Pixels 
	private Dimension getImagePixelsSize() 
	{
		MediaTracker mTracker = new MediaTracker(this);
		mTracker.addImage(image, 1);
		try {
			mTracker.waitForID(1);
			} catch (InterruptedException e) {
				
			}
		return new Dimension(image.getWidth(null), image.getHeight(null));
	}
	
	
	// Returns image size in Dpi
	private Dimension getImageDpiSize()
	{
		Dimension imageSize = getImagePixelsSize();
		
		int width = (int) (imageSize.width / getPixelsPerInch() * getImageDpi());
		int heigth = (int) (imageSize.height / getPixelsPerInch() * getImageDpi());
		
		return new Dimension(width, heigth);
	}
	
	
	// Returns pixels in 1 inch
	public int getPixelsPerInch()
	{
		return Toolkit.getDefaultToolkit().getScreenResolution();
	}
	
	
	// Returns dpi of the image
	private long getImageDpi()
	{
		// потому что не знаем реальное Dpi,
                             // но для вычисления макс размеров печати Ок
                             return DOTS_PER_INCH; 
	}
}